package com.duanjw.springcloud.nacos.client.web;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 服务发现 controller
 *
 * @author duanjw
 */
@RestController
@RequestMapping("discovery")
public class DiscoveryController {

    private final NacosServiceManager nacosServiceManager;
    private final NacosDiscoveryProperties nacosDiscoveryProperties;

    public DiscoveryController(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties) {
        this.nacosServiceManager = nacosServiceManager;
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
    }

    /**
     * 根据服务名获取注册中心的服务
     * curl localhost:7001/discovery/nacos-client
     *
     * @param serviceName 服务名
     * @return 服务列表
     * @throws NacosException
     */
    @GetMapping("{serviceName}")
    public List<Instance> list(@PathVariable String serviceName) throws NacosException {
        return nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties()).getAllInstances(serviceName);
    }

    /**
     * 向注册中心注册服务
     * curl -X POST 'localhost:7001/discovery?serviceName=example&ip=127.0.0.1&port=8080'
     * curl localhost:7001/discovery/example
     *
     * @param serviceName 服务名
     * @param ip          ip 地址
     * @param port        端口
     * @return 是否注册成功
     * @throws NacosException
     */
    @PostMapping
    public boolean register(String serviceName, String ip, Integer port) throws NacosException {
        nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties()).registerInstance(serviceName, ip, port);
        return true;
    }
}
